﻿#region codejockey.net Copyright Banner
/***************************************************************\
 * Copyright 2010 codejockey.net.                                *
 *                                                               *
 * This code is property of codejockey.net and cannot be used    *
 * without explicit permission given by a codejockey.net         *
 * Representative.  For details contact: source@codejockey.net   *
 \***************************************************************/
#endregion

#region Using Statements

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

#endregion

namespace codejockey.Web.HTTPModules.AutoVersion
{
    /// <summary>
    /// AutoVersionHTTPModule is a custom HTTP module that allows for auto-versioning
    /// of various web assets.
    /// </summary>
    public class AutoVersionHTTPModule : IHttpModule
    {
        #region Private Methods

        #endregion

        #region Public Methods

        public void context_BeginRequest(object sender, EventArgs e)
        {
            context.Response.Filter = new VersionModStream(context.Response.Filter);
        }

        #endregion

        #region IHttpModule Members

        HttpApplication context;

        public void Dispose()
        {
            // Nothing to dispose of.
        }

        public void Init(HttpApplication context)
        {
            this.context = context;
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        #endregion
    }

    public class VersionModStream : MemoryStream
    {
        // Private members
        private Stream m_outputStream;

        // Ctor
        public VersionModStream(Stream outputStream)
        {
            InitStream(outputStream);
        }

        private void InitStream(Stream outputStream)
        {
            m_outputStream = outputStream;
        }

        // Write method does it
        public override void Write(byte[] buffer, int offset, int count)
        {
            // Gets a string out of input bytes
            Encoding enc = HttpContext.Current.Response.ContentEncoding;
            string outPut = enc.GetString(buffer, offset, count);

            outPut = outPut.Replace(".css", ".css?v1.0");
            outPut = outPut.Replace(".js", ".js?v1.0");

            // Renders the string back to an array of bytes
            byte[] data = enc.GetBytes(outPut);

            // Persists changes back to the response stream
            m_outputStream.Write(data, 0, outPut.Length);
        }
    }
}
